package org.dromara.bykt.controller;

import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.NotImplementedException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.dromara.bykt.domain.bo.BYKTSysUserBo;
import org.dromara.bykt.domain.vo.BYKTSysUserImportVo;
import org.dromara.bykt.domain.vo.BYKTSysUserVo;
import org.dromara.bykt.listener.BYKTSysUserImportListener;
import org.dromara.bykt.service.IBYKTSysUserService;
import org.dromara.bykt.utils.AliOSSUpload;
import org.dromara.bykt.utils.ByteArrayMultipartFile;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.utils.SpringUtils;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.excel.core.ExcelResult;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.web.core.BaseController;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 用户信息
 *
 * @author Hou
 * @date 2025-07-01
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/bykt/user")
public class BYKTSysUserController extends BaseController {

    private final IBYKTSysUserService sysUserService;

    /**
     * 查询用户信息列表
     */
    @GetMapping("/list")
    public TableDataInfo<BYKTSysUserVo> list(BYKTSysUserBo bo, PageQuery pageQuery) {
        return sysUserService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出用户信息列表
     */
    @Log(title = "用户信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response) {
        ExcelUtil.exportExcel(null, "用户信息", BYKTSysUserVo.class, response);
    }

    /**
     * 获取用户信息详细信息
     *
     * @param userId 主键
     */
    @GetMapping("/{userId}")
    public R<BYKTSysUserVo> getInfo(@NotNull(message = "主键不能为空")
                                    @PathVariable Long userId) {
        return R.ok(sysUserService.queryById(userId));
    }

    /**
     * 新增用户信息
     */
    @Log(title = "用户信息", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody BYKTSysUserBo bo) {
        return toAjax(sysUserService.insertByBo(bo));
    }

    /**
     * 修改用户信息
     */
    @Log(title = "用户信息", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody BYKTSysUserBo bo) {
        return toAjax(sysUserService.updateByBo(bo));
    }

    /**
     * 删除用户信息
     *
     * @param userIds 主键串
     */
    @Log(title = "用户信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] userIds) {
        return toAjax(sysUserService.deleteWithValidByIds(List.of(userIds), true));
    }

//    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
//    @PostMapping(value = "/importData", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
//    public R<Void> userImportData(@RequestPart("file") MultipartFile file, boolean updateSupport) throws Exception {
//        // 1. 读取Excel文件
//        Workbook workbook = new XSSFWorkbook(file.getInputStream());
//
//        List<? extends PictureData> allPictures = workbook.getAllPictures();
//        // 2. 获取所有图片数据
//        Map<String, byte[]> pictureMap = new HashMap<>();
//
//        // 3. 处理每张图片并上传到OSS
//        for (int i = 0; i < allPictures.size(); i++) {
//            PictureData picture = allPictures.get(i);
//            byte[] data = picture.getData();
//            String ext = picture.suggestFileExtension();
//            String fileName = System.currentTimeMillis() + "_" + i + "." + ext;
//
//            pictureMap.put("ID_" + picture.getMimeType(), ossUrl); // 使用图片ID作为key
//        }
//
//        // 4. 创建自定义的监听器，传入图片映射
//        BYKTSysUserImportListener listener = new BYKTSysUserImportListener(updateSupport, pictureMap);
//
//        // 5. 导入Excel数据
//        ExcelResult<BYKTSysUserImportVo> result = ExcelUtil.importExcel(
//            file.getInputStream(),
//            BYKTSysUserImportVo.class,
//            listener
//        );
//
//        return R.ok(result.getAnalysis());
//
//        return R.ok(result.getAnalysis());
//    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PostMapping(value = "/importData", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<Void> userImportData(@RequestPart("file") MultipartFile file, boolean updateSupport) throws Exception {
        // 1. 读取Excel文件
        Workbook workbook = new XSSFWorkbook(file.getInputStream());

        // 2. 获取所有图片数据并上传到OSS
        Map<String, String> pictureMap = processExcelImages(workbook);

        // 3. 创建自定义监听器并导入数据
        BYKTSysUserImportListener listener = new BYKTSysUserImportListener(updateSupport, pictureMap);
        ExcelResult<BYKTSysUserImportVo> result = ExcelUtil.importExcel(
            file.getInputStream(),
            BYKTSysUserImportVo.class,
            listener
        );

        return R.ok(result.getAnalysis());
    }

    // 处理Excel中的图片并上传到OSS
    private Map<String, String> processExcelImages(Workbook workbook) throws Exception {
        Map<String, String> pictureMap = new HashMap<>();
        List<? extends PictureData> pictures = workbook.getAllPictures();
        AliOSSUpload ossUpload = SpringUtils.getBean(AliOSSUpload.class); // 使用SpringUtils获取Bean

        for (int i = 0; i < pictures.size(); i++) {
            PictureData picture = pictures.get(i);
            byte[] data = picture.getData();
            String ext = picture.suggestFileExtension();
            String fileName = System.currentTimeMillis() + "_" + i + ".jpg";

            // 创建临时MultipartFile
            MultipartFile multipartFile = new ByteArrayMultipartFile(
                data,
                fileName,
                fileName,
                "image/" + ext
            );

            // 上传到OSS
            String ossUrl = ossUpload.uploadImage(multipartFile);
            pictureMap.put("picture_" + i, ossUrl); // 使用图片ID作为key
        }

        return pictureMap;
    }

}
